package com.kk.demo.handler;

import com.kk.demo.result.GlobalResult;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * the type of spring-boot-prototype
 *
 * <p>
 * .
 *
 * @author 王志强
 * @date 2022-11-15
 */
@RestControllerAdvice(basePackages = "com.kk.demo.controller")
public class GlobalHandler {

    /**
     * 全局异常
     */
    @ExceptionHandler({
            NullPointerException.class
    })
    public GlobalResult handler(NullPointerException e) {
        System.out.println("NullPointerException!" + e.getMessage());
        return new GlobalResult<>("1", "NullPointerException ", null);
    }


    /**
     * 全局异常
     */
    @ExceptionHandler({
            ArithmeticException.class,
            IllegalArgumentException.class
    })
    public GlobalResult handler(Exception e) {
        System.out.println(e.toString());
        return new GlobalResult<>("2", e.toString(), null);
    }

    /**
     * 全局异常
     */
/*    @ExceptionHandler(NullPointerException.class)
    public String handler(NullPointerException e) {
        System.out.println("哦豁，报空指针了！！！");
        GlobalResult<String> stringGlobalResult = new GlobalResult<>("code123","msg-nihao ","");
        return stringGlobalResult.toJsonStr();
    }*/


    /**
     * 全局日期绑定定义。
     *
     * @param binder
     * @InitBinder方法会帮助我们把String类型的参数先trim再绑定，而对于Date类型的参数会先格式化再绑定
     */
    @InitBinder
    public void globalInitBinder(WebDataBinder binder) {
        // 定义前端传参格式
        binder.registerCustomEditor(Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyyy=MM=dd"), false));
    }


    /**
     * 将所有输出的信息都加上当前的平台信息，比如版本等公共信息
     *
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("msg", "hello");

        HashMap<String, String> map = new HashMap<>(16);
        map.put("version", "1.0.0");
        map.put("name", "博客园4587");
        model.addAttribute("platform", map);
    }
}
